library(tidyverse) # for data cleaning and plotting
library(googlesheets4) # for reading googlesheet data
library(lubridate) # for date manipulation
library(openintro) # for the abbr2state() function
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
library(ggmap) # for mapping points on maps
library(gplots) # for col2hex() function
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
library(leaflet) # for highly customizable mapping
library(carData) # for Minneapolis police stops data
library(ggthemes) # for more themes (including theme_map())
gs4_deauth() # To not have to authorize each time you knit.
theme_set(theme_minimal())
# Starbucks locations
Starbucks <- read_csv("https://www.macalester.edu/~ajohns24/Data/Starbucks.csv")
starbucks_us_by_state <- Starbucks %>%
filter(Country == "US") %>%
count(`State/Province`) %>%
mutate(state_name = str_to_lower(abbr2state(`State/Province`)))
# Lisa's favorite St. Paul places - example for you to create your own data
favorite_stp_by_lisa <- tibble(
place = c("Home", "Macalester College", "Adams Spanish Immersion",
"Spirit Gymnastics", "Bama & Bapa", "Now Bikes",
"Dance Spectrum", "Pizza Luce", "Brunson's"),
long = c(-93.1405743, -93.1712321, -93.1451796,
-93.1650563, -93.1542883, -93.1696608,
-93.1393172, -93.1524256, -93.0753863),
lat = c(44.950576, 44.9378965, 44.9237914,
44.9654609, 44.9295072, 44.9436813,
44.9399922, 44.9468848, 44.9700727)
)
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
If you were not able to get set up on GitHub last week, go here and get set up first. Then, do the following (if you get stuck on a step, don’t worry, I will help! You can always get started on the homework and we can figure out the GitHub piece later):
keep_md: TRUE in the YAML heading. The .md file is a markdown (NOT R Markdown) file that is an interim step to creating the html file. They are displayed fairly nicely in GitHub, so we want to keep it and look at it there. Click the boxes next to these two files, commit changes (remember to include a commit message), and push them (green up arrow).Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Mapping data with R” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
ggmap)Starbucks locations to a world map. Add an aesthetic to the world map that sets the color of the points according to the ownership type. What, if anything, can you deduce from this visualization?world <- get_stamenmap(
bbox = c(left = -180, bottom = -57, right = 179, top = 82.1),
maptype = "terrain",
zoom = 2)
ggmap(world) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude, color = `Ownership Type`),
alpha = .3,
size = .2) +
theme_map()
I find that there are very few Starbucks in Australia.
mn_map <- get_stamenmap(
bbox = c(left = -93.4, bottom = 44.9, right = -93.0, top = 45.1),
maptype = "terrain",
zoom = 13)
# Don't actually need
# starbucks_twin_cities <- Starbucks %>%
# filter(Country == "US" & `State/Province` == "MN") %>%
# filter(City == "Minneapolis"| City == "St. Paul")
ggmap(mn_map) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude)) +
theme_map()
Decreasing - Zoom in / Increasing - Zoom out
get_stamenmap() in help and look at maptype). Include a map with one of the other map types.mn_map <- get_stamenmap(
bbox = c(left = -93.4, bottom = 44.9, right = -93.0, top = 45.1),
maptype = "toner-hybrid",
zoom = 13)
ggmap(mn_map) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude)) +
theme_map()
annotate() function (see ggplot2 cheatsheet).mn_map <- get_stamenmap(
bbox = c(left = -93.4, bottom = 44.9, right = -93.0, top = 45.1),
maptype = "terrain",
zoom = 10)
ggmap(mn_map) +
geom_point(aes(x = -93.1712321, y = 44.9378965),
size = 8,
color = "orange",
shape = 6) +
annotate("text", x = -93.1712321, y = 44.9378965, label = "Macalester College") +
theme_map()
geom_map())The example I showed in the tutorial did not account for population of each state in the map. In the code below, a new variable is created, starbucks_per_10000, that gives the number of Starbucks per 10,000 people. It is in the starbucks_with_2018_pop_est dataset.
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>% # Read-in the csv data.
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>% # remove the dot at the beginning of each state name.
mutate(state = str_to_lower(state)) # mutate each state name to lower case, preparing for the join later.
starbucks_with_2018_pop_est <-
starbucks_us_by_state %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>% # join the # of Starbucks and # of ppl data together by the state name.
mutate(starbucks_per_10000 = (n/est_pop_2018)*10000) # scales to per 10,000 people.
dplyr review: Look through the code above and describe what each line of code does. See comments in the code.
Create a choropleth map that shows the number of Starbucks per 10,000 people on a map of the US. Use a new fill color, add points for all Starbucks in the US (except Hawaii and Alaska), add an informative title for the plot, and include a caption that says who created the plot (you!). Make a conclusion about what you observe.
states_map <- map_data("state")
starbucks_us_by_state %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state_name,
fill = starbucks_with_2018_pop_est$starbucks_per_10000)) +
geom_point(data = Starbucks %>%
filter(Country == "US" & `State/Province` != "AK" & `State/Province` != "HI"),
aes(x = Longitude, y = Latitude),
size = .05,
alpha = .2,
color = "goldenrod") +
expand_limits(x = states_map$long, y = states_map$lat) +
labs(title = "Starbucks in U.S",
fill = guide_legend(title = "Starbucks per 10,000"),
caption = "@Kaiyang Yao") +
scale_fill_viridis_c(option = "heat") +
theme_map() +
theme(legend.background = element_blank())
The number of Starbucks per 10,000 people are higher in west coasts.
leaflet)Create a data set using the tibble() function that has 10-15 rows of your favorite places. The columns will be the name of the location, the latitude, the longitude, and a column that indicates if it is in your top 3 favorite locations or not. For an example of how to use tibble(), look at the favorite_stp_by_lisa I created in the data R code chunk at the beginning.
Create a leaflet map that uses circles to indicate your favorite places. Label them with the name of the place. Choose the base map you like best. Color your 3 favorite places differently than the ones that are not in your top 3 (HINT: colorFactor()). Add a legend that explains what the colors mean.
Connect all your locations together with a line in a meaningful way (you may need to order them differently in the original data).
If there are other variables you want to add that could enhance your plot, do that now.
favorite_stp_by_Kaiyang <- tibble(
place = c("Home", "Shopping Mall", "High School", "Hot Pot", "Airport", "Fav Park", "Muwu Barbeque", "Cinema", "Subway Station", "Baiwang Mountain"),
long = c(116.2778020, 116.321751, 116.320708, 116.301355, 116.619758, 116.396797, 116.358615, 116.277505, 116.280499, 116.262991),
lat = c(40.0310626, 39.984237, 39.980479, 39.979809, 40.072776, 40.025231, 40.010871, 40.021275, 40.038756, 40.036722),
top3 = c(FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
)
# Numeric
pal <- colorFactor(c("#00B4EF", "#FF6C90"),
domain = favorite_stp_by_Kaiyang$top3)
leaflet(data = favorite_stp_by_Kaiyang) %>%
addProviderTiles(providers$Stamen.Watercolor) %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~place,
weight = 10,
opacity = 1,
color = ~pal(top3)) %>%
addPolylines(lng = ~long,
lat = ~lat,
color = col2hex("skyblue1")) %>%
addLegend(pal = pal,
values = ~top3,
title = "Top 3 place",
position = "bottomright")
This section will revisit some datasets we have used previously and bring in a mapping component.
The data come from Washington, DC and cover the last quarter of 2014.
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}. This code reads in the large dataset right away.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data-Small.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. This time, plot the points on top of a map. Use any of the mapping tools you’d like.##################
# GGmap Approach
##################
# dc_map <- get_stamenmap(
# bbox = c(left = -77.2, bottom = 38.8, right = -76.9, top = 39.1),
# maptype = "terrain",
# zoom = 9)
# ggmap(dc_map) +
# geom_point(data = departure_by_station,
# aes(x = long,
# y = lat,
# color = n),
# alpha = .8,
# shape = 17) +
# scale_color_viridis_c() +
# theme_map() +
# theme(legend.background = element_blank())
##################
# Leaflet Approach
##################
departure_by_station <- Trips %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
group_by(lat, long) %>%
summarize(n = n(),
prop_causal = mean(client == "Casual")) # for next problem
leaflet(data = departure_by_station) %>%
addTiles() %>%
addCircles(lng = ~long,
lat = ~lat,
weight = ~n/10,
opacity = .8,
color = col2hex("purple"))
leaflet(data = departure_by_station) %>%
addTiles() %>%
addCircles(lng = ~long,
lat = ~lat,
weight = ~prop_causal*20,
opacity = .8)
Stations near mall and park have more casual users. Stations in main bussiness streets have more licensed users.
The following exercises will use the COVID-19 data from the NYT.
recent_cases <- covid19 %>%
group_by(state, fips) %>%
summarize(max = max(cases)) %>%
mutate(state = str_to_lower(state))
states_map <- map_data("state")
recent_cases %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state,
fill = max)) +
expand_limits(x = states_map$long, y = states_map$lat) +
labs(title = "Most recent cumulative cases",
fill = guide_legend(title = "Cases")) +
scale_fill_viridis_c(option = "plasma") +
theme_map() +
theme(legend.background = element_blank())
Problem: the population base in each state is different, so the visualization is biased,
recent_cases_10000 <-
recent_cases %>%
left_join(census_pop_est_2018,
by = "state") %>%
mutate(cases_per_10000 = (max/est_pop_2018)*10000)
recent_cases_10000 %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state,
fill = cases_per_10000)) +
expand_limits(x = states_map$long, y = states_map$lat) +
labs(title = "Most recent cumulative cases per 10000 people",
fill = guide_legend(title = "Cases per 10000")) +
scale_fill_viridis_c(option = "plasma") +
theme_map() +
theme(legend.background = element_blank())
recent_four_days_10000 <-
covid19 %>%
filter(date == "2020-6-1" | date == "2020-8-1" |
date == "2020-10-1" | date == "2020-11-1") %>%
mutate(state = str_to_lower(state)) %>%
left_join(census_pop_est_2018,
by = "state") %>%
mutate(cases_per_10000 = (cases/est_pop_2018)*10000)
recent_four_days_10000 %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state,
fill = cases_per_10000)) +
expand_limits(x = states_map$long, y = states_map$lat) +
facet_wrap(vars(date)) +
labs(title = "Most recent cumulative cases per 10000 people",
fill = guide_legend(title = "Cases per 10000")) +
scale_fill_viridis_c(option = "plasma") +
theme_map() +
theme(legend.background = element_blank())
## Minneapolis police stops
These exercises use the datasets MplsStops and MplsDemo from the carData library. Search for them in Help to find out more information.
MplsStops dataset to find out how many stops there were for each neighborhood and the proportion of stops that were for a suspicious vehicle or person. Sort the results from most to least number of stops. Save this as a dataset called mpls_suspicious and display the table.mpls_suspicious <- MplsStops %>%
group_by(neighborhood) %>%
summarize(n = n(),
prop_suspicious = mean(problem == "suspicious")) %>%
arrange(desc(prop_suspicious))
mpls_suspicious
leaflet map and the MplsStops dataset to display each of the stops on a map as a small point. Color the points differently depending on whether they were for suspicious vehicle/person or a traffic stop (the problem variable). HINTS: use addCircleMarkers, set stroke = FAlSE, use colorFactor() to create a palette.pal <- colorFactor(c("cyan3", "tomato"),
domain = MplsStops$problem)
leaflet(data = MplsStops) %>%
addTiles() %>%
addCircleMarkers(
lng = ~long,
lat = ~lat,
weight = .3,
color = ~pal(problem),
stroke = FALSE) %>%
addLegend(pal = pal,
values = ~problem,
position = "bottomleft")
eval=FALSE. Although it looks like it only links to the .sph file, you need the entire folder of files to create the mpls_nbhd data set. These data contain information about the geometries of the Minneapolis neighborhoods. Using the mpls_nbhd dataset as the base file, join the mpls_suspicious and MplsDemo datasets to it by neighborhood (careful, they are named different things in the different files). Call this new dataset mpls_all.mpls_nbhd <- st_read("Minneapolis_Neighborhoods/Minneapolis_Neighborhoods.shp", quiet = TRUE)
mpls_demo <- MplsDemo
mpls_all <-
mpls_nbhd %>%
left_join(mpls_suspicious,
by = c("BDNAME" = "neighborhood")) %>%
left_join(mpls_demo,
by = c("BDNAME" = "neighborhood"))
# mpls_nbhd %>%
# anti_join(mpls_suspicious,
# by = c("BDNAME" = "neighborhood"))
#
# mpls_suspicious %>%
# anti_join(mpls_nbhd,
# by = c("neighborhood" = "BDNAME"))
leaflet to create a map from the mpls_all data that colors the neighborhoods by prop_suspicious. Display the neighborhood name as you scroll over it. Describe what you observe in the map.pal <- colorNumeric("viridis",
domain = mpls_all$prop_suspicious)
leaflet(mpls_all) %>%
addTiles() %>%
addPolygons(
fillColor = ~pal(prop_suspicious),
fillOpacity =0.7,
popup = ~paste(BDNAME)
) %>%
addLegend(pal = pal,
values = ~prop_suspicious,
opacity = 0.5,
title = "prop suspicious",
position = "bottomright")
The proportion of suspicious is higher in the south part of MN.
leaflet to create a map of your own choosing. Come up with a question you want to try to answer and use the map to help answer that question. Describe what your map shows.Question: show the proportion of black in each neighborhood.
pal <- colorNumeric("viridis",
domain = mpls_all$black)
leaflet(mpls_all) %>%
addTiles() %>%
addPolygons(
fillColor = ~pal(black),
fillOpacity =0.7,
popup = ~paste(BDNAME)
) %>%
addLegend(pal = pal,
values = ~black,
opacity = 0.5,
title = "prop black",
position = "bottomright")
It shows the proportion of black people is higher in the north part of MN.
DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?